<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>动态显示时间(Dynamic display time)</title>
</head>
<body>
  
  <div class="time">2024-09-17 14:35:55</div>

  <script>
    // 1. 获取需要操作的对象
    const timeEl = document.querySelector('.time')

    // 2. 定义一个函数，用于显示时间
    function showTime() {
      // 2.1 获取当前时间
      const now = new Date()
      // 2.2 获取年月日时分秒
      // 2.2.1 获取年
      const year = now.getFullYear()
      // 2.2.2 获取月
      const month = padLeft(now.getMonth() + 1)
      // 2.2.3 获取日
      const date = padLeft(now.getDate())
      // 2.2.4 获取小时
      const hour = padLeft(now.getHours())
      // 2.2.5 获取分钟
      const minute = padLeft(now.getMinutes())
      // 2.2.6 获取秒
      const second = padLeft(now.getSeconds())

      timeEl.textContent = `${year}-${month}-${date} ${hour}:${minute}:${second}`
    }

    function padLeft(str) {
      return str.toString().padStart(2, '0')
    }

    setInterval(showTime, 1000)
    
  </script>
  
</body>
</html>